package com.tangqihang229350526.mynote.database

import android.R.attr.password
import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper


class UserDatabase (context: Context?) :
    SQLiteOpenHelper(context, DB_NAME, null, V) {
    init {
        val db = writableDatabase
        db.execSQL(
            "create table IF NOT EXISTS " + User_TABLE_NAME
                    + "(id integer primary key autoincrement, username varchar, password varchar)"
        )
        val c: Cursor =
            db.rawQuery("SELECT COUNT(*) FROM $User_TABLE_NAME WHERE username = ?", arrayOf<String>("tangshuai"))
        c.moveToFirst()
        val count: Int = c.getInt(0)
        c.close()

        // 如果用户名不存在，则插入新的用户记录
        if (count == 0) {
            val values = ContentValues()
            values.put("username", "tangshuai")
            values.put("password", "229350526")
            db.insert(User_TABLE_NAME, null, values)
        }
    }

    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL(
            "create table IF NOT EXISTS " + User_TABLE_NAME
                    + "(id integer primary key autoincrement, username varchar, password varchar)"
        )
    }

    fun register(username:String?,password:String?): Boolean {
        val database = this.writableDatabase
        val values = ContentValues()
        values.put("username", username)
        values.put("password", password)
        val c: Cursor =
            database.rawQuery("SELECT COUNT(*) FROM $User_TABLE_NAME WHERE username = ? and password = ?", arrayOf<String?>(username,password))
        c.moveToFirst()
        val count: Int = c.getInt(0)
        c.close()
        return if (count == 0){
            database.insert(User_TABLE_NAME, null, values)
            true
        }else{
            false
        }

    }

    @SuppressLint("Recycle")
    fun login(username:String?, password:String?):Boolean {
        val database = this.writableDatabase
        val values = ContentValues()
        values.put("username", username)
        values.put("password", password)
        val c: Cursor =
            database.rawQuery("SELECT COUNT(*) FROM $User_TABLE_NAME WHERE username = ? and password = ?", arrayOf<String?>(username,password))
        c.moveToFirst()
        val count: Int = c.getInt(0)
        c.close()
        return count != 0
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
    }

    companion object {
        private const val User_TABLE_NAME = "MyUser"
        private const val DB_NAME = "mynote.db"
        private const val V = 1
    }
}